import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;

/**
 * Created by jiaming.jiang on 2017/3/8.
 */
public class TestTreeSet {

    private static final TreeSet<String> dates = new TreeSet<>();

    private static final String YYYYMMDD = "yyyyMMdd";

    static{
        //取2005-01-01 至 2025年的日期
        DateTime startTime= new DateTime(2005,01,01,00,00);
        DateTime nowTime = new DateTime(2025,01,01,00,00);
        int days = Days.daysBetween(startTime, nowTime).getDays();
        for(int i=1;i<=days;i++){
            String yyyyMMdd = startTime.plusDays(i).toString(YYYYMMDD);
            dates.add(yyyyMMdd);
        }
    }

    public static void main(String[] args) {
        NavigableSet<String> timeInterval = getTimeInterval("2010", "2022");

        Iterator<String> stringIterator =
                timeInterval.descendingIterator();
        while (stringIterator.hasNext()) {
            System.out.println(stringIterator.next());
        }


    }
    private TestTreeSet(){
    }

    /**
     * 获取时间区间
     * @param startTime
     * @param endTime
     * @return SortedSet
     */
    public static NavigableSet<String> getTimeInterval(String startTime,String endTime){
        if(StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)){
            throw new RuntimeException("startTime或endTime不能为null");
        }
        NavigableSet<String> s = dates.subSet(startTime, true, endTime, true);
        return s;
    }

    /**
     * 获取指定日期的偏移日期
     * @param date
     * @param offsets 偏移量，负数向前，正数向后（如：getDate("20170203",-1)返回"20170202"）
     * @return
     */
    public static String getDate(String date, int offsets){
        DateTimeFormatter format = DateTimeFormat.forPattern(YYYYMMDD);
        DateTime dateTime = DateTime.parse(date, format);
        dateTime = dateTime.plusDays(offsets);
        return dateTime.toString(YYYYMMDD);
    }

    /**
     * 获取指定日期的偏移日期
     * @param date
     * @param offsets 偏移量，负数向前，正数向后（如：getDate("20170203",-1)返回"20170202"）
     * @return
     */
    public static NavigableSet<String> getTimeInterval(String startDate,int length){
        if(length < 0) {
            return null;
        }
        String endDate = getDate(startDate, length -1);
        return getTimeInterval(startDate,endDate);
    }

}
